﻿using UnityEngine;
namespace zserialize
{
public class SerializableFieldContainerBehaviour : MonoBehaviour, ISerializableFieldContainer
{
    [HideInInspector]
    public byte[] data;
    public Object[] unityObjs;
    private FieldDictionary fields;

    public FieldDictionary GetFieldDictionary()
    {
        Init();
        return fields;
    }

    void Init()
    {
        if (data == null)
        {
            return;
        }

        if (fields != null)
        {
            return;
        }

        fields = SerializableFieldContainerHelper.ReadFromBytes(data, unityObjs);
    }

    public override string ToString()
    {
        string s = base.ToString();

        string dataObjLog = "data(" + (data == null ? "null" : data.Length.ToString()) + "): ";
        if(data != null)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(data.Length * 3);
            for(int i = 0; i < data.Length; i++)
            {
                if (i != 0 && i % 8 == 0)
                {
                    sb.Append("| ");
                }

                byte b = data[i];
                sb.Append(System.Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            }

            dataObjLog += sb.ToString();
            string dataStr = System.Text.Encoding.UTF8.GetString(data);

            dataStr = dataStr.Replace("\0", @"\0");
            dataObjLog += "(" + dataStr.Length + "|" + dataStr + ")";
        }

        string unityObjLog = "unityObjs(" + (unityObjs == null ? "null" : unityObjs.Length.ToString()) + "): ";
        if (unityObjs != null)
        {
            for (int i = 0; i < unityObjs.Length; i++)
            {
                Object obj = unityObjs[i];
                unityObjLog += "(" + i + "," + obj + "," + (obj != null ? obj.GetType().ToString() : "null") + "), ";
            }
        }


        s += "\n" + dataObjLog;
        s += "\n" + unityObjLog;
        s += "\n" + "fields:" + fields;

        return s;
    }

    public void Clear()
    {
        data = null;
        unityObjs = null;
        if(fields != null)
        {
            fields.Clear();
            fields = null;
        }
    }
}
}